package com.example.demo.redis;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedissionReentrantLockController {

    public static void main(String[] args) {
        // 创建 Redisson 客户端配置
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://1.92.80.47:6379")
                .setPassword("ysb..qd..")
                .setDatabase(1);

        // 创建 Redisson 客户端
        RedissonClient redisson = Redisson.create(config);

        // 获取可重入锁对象
        RLock reentrantLock = redisson.getLock("myReentrantLock");

        try {
            // 获取锁
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + " 获取锁");

            // 在持有锁的情况下再次获取锁
            reentrantLock.lock();
            System.out.println(Thread.currentThread().getName() + " 再次获取锁");

            // 执行任务，模拟工作
            System.out.println(Thread.currentThread().getName() + " 正在执行任务...");

        } finally {
            // 释放锁
            reentrantLock.unlock();
            System.out.println(Thread.currentThread().getName() + " 释放锁");

            // 在持有锁的情况下再次释放锁
            reentrantLock.unlock();
            System.out.println(Thread.currentThread().getName() + " 再次释放锁");
        }

        // 关闭 Redisson 客户端
        redisson.shutdown();
    }

}
